package com.readword.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import org.apache.poi.POIXMLException;
import org.apache.poi.xwpf.usermodel.IBodyElement;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFPicture;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* @ClassName: WordUtil
* @Description: word文档操作工具
* @author 码农小鹿
* @date 2024年1月10日 下午1:46:32
*
 */
public class WordUtil {
	XWPFDocument docXml = null;

	private final static Logger logger = LoggerFactory.getLogger(WordUtil.class);
	
	/**
	 * 调用方的所有异常都证明word文件读取失败，特别注意一下就是：
	 * 只有docx才可以通过普通的jar包方式去读取，doc是读取不到具体样式内容的，比如图片
	 * @param templateIO
	 * @throws POIXMLException
	 * @throws IOException
	 */
	public WordUtil(InputStream templateIO) throws POIXMLException, IOException {
		docXml = new XWPFDocument(templateIO);
	}
	
	/**
	 * 读取文档内容与保存图片
	 * @return
	 */
	public String read() {
		logger.info("开始读取word文档");
		List<IBodyElement>  ibodyList = docXml.getBodyElements();
		StringBuilder sb = new StringBuilder();
		for (int pIndex = 0; pIndex < ibodyList.size(); pIndex++) {
			IBodyElement element = ibodyList.get(pIndex);
			if (element instanceof XWPFParagraph) {
				XWPFParagraph paragraph = (XWPFParagraph) element;
				List<XWPFRun> runs = paragraph.getRuns();
				for (int r = 0; r < runs.size(); r++) {
					XWPFRun run = runs.get(r);
					String text = runs.get(r).getText(0);
					if(null != text) {
						sb.append(text);
					}
					List<XWPFPicture> pics = run.getEmbeddedPictures();
					for (int p = 0; p < pics.size(); p++) {
						XWPFPicture pic = pics.get(p);
						sb.append("${" + Cons.TOOLS.saveFile(pic) + "}");
	                }
				}
			}
		}
		return sb.toString();
	}
	
	public static InputStream getFile(String path) throws FileNotFoundException {
		InputStream inputStream = new FileInputStream(path);
		return inputStream;
	}
	
	public static OutputStream getFileOutputIo(String path) throws FileNotFoundException {
		OutputStream outputStream = new FileOutputStream(path);
		return outputStream;
	}
	
}
